// License Notification
//======================================================
// Copyright (c) 2010 Channel Intelligence Inc.
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// which accompanies this distribution, and is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// ======================================================




using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using CIP4.Common;

namespace CIP4.Installer
{
    /// <summary>
    /// Consider using SqlCommand for this - see http://support.microsoft.com/kb/307283
    /// </summary>
    class SqlScriptProcessorType
    {
        public delegate void ErrorMsgDelegate(string msg);

        public delegate void InfoMsgDelegate(string msg);

        public static string ProcessSqlScript(string sqlText, string host, string databaseName, string location, InfoMsgDelegate InfoMsg, ErrorMsgDelegate ErrorMsg)
        {
            sqlText = sqlText.Replace("<database name - do not edit this text>", databaseName);
            sqlText = sqlText.Replace("<database location - do not edit this text>", location);
            string _ConnectionString1 =
                string.Format("Connect Timeout=60;Data Source={0};Initial Catalog=master;Integrated Security=SSPI", host);

            string _ConnectionStringFoo =
                string.Format("Connect Timeout=60;Data Source={0};Initial Catalog={1};Integrated Security=SSPI", host, databaseName);

            string _ConnectionString = _ConnectionString1;

            string[] commands = sqlText.Replace("\r\ngo\r\n", "\r\nGO\r\n").Split(new string[] { "\r\nGO\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            int commandsProcessed = 0;

            foreach (string commandText in commands)
            {
                try
                {
                    if (commandText.ToLower().Contains("use [" + databaseName.ToLower() + "]"))
                        _ConnectionString = _ConnectionStringFoo;

                    using (SqlConnection connection = new SqlConnection(_ConnectionString))
                    {
                        connection.Open();
                        SqlCommand _Command = connection.CreateCommand();
                        _Command.CommandType = System.Data.CommandType.Text;
                        _Command.CommandText = commandText;
                        int _Rows = _Command.ExecuteNonQuery();
                        if (_Rows == 0)
                        {
                            ErrorMsg("Unexpected sql schema process result - check the database");
                        }
                        else
                        {
                            commandsProcessed += 1;
                        }
                    }
                }
                catch (System.Data.SqlClient.SqlException ex) 
                {
                    if (ex.Message.Contains("already exists"))
                    {
                        InfoMsg(String.Format("Database {0} already exists", databaseName));
                        return sqlText;
                    }
                    ErrorMsg(string.Format("Unexpected exception processing\n{0}\nIn {1}\n{2}", commandText, _ConnectionString, ex.ToString()));
                    return string.Empty;
                }
                catch (Exception ex)
                {
                    ErrorMsg(string.Format("Unexpected exception processing\n{0}\nIn {1}\n{2}", commandText, _ConnectionString, ex.ToString()));
                    return string.Empty;
                }
            }
            InfoMsg(string.Format("Setup DataProvider {0} at {1} completed: {2} commands found {3} commands processed",
                databaseName, location, commands.Length, commandsProcessed));
            return sqlText;
        }
    }
}
